package top.yudoge.dogeeditorserverj.db;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.yudoge.dogeeditorserverj.common.utils.CommonUtil;
import top.yudoge.dogeeditorserverj.db.config.SQLDataSource;
import top.yudoge.dogeeditorserverj.db.config.SQLDataSourceProperties;
import top.yudoge.dogeeditorserverj.db.exceptions.BootStrapError;

import java.util.*;

@Component
public class SQLDataSourceConnectorHolder {

    @Autowired
    private SQLDataSourceProperties properties;

    /**
     * Map<数据源名称, 数据源连接器>
     */
    private Map<String, SQLDataSourceConnector> connectorMap;

    @PostConstruct
    public void init() {
        connectorMap = new LinkedHashMap<>();
        List<SQLDataSource> sqlDataSources = properties.getDataSources();
        for (SQLDataSource sqlDataSource : sqlDataSources) {
            SQLDataSourceConnector connector = SQLDataSourceConnectorFactory.fromSQLDataSource(sqlDataSource);
            if (connectorMap.containsKey(sqlDataSource.getName())) {
                throw new BootStrapError("Duplicated data source name => " + sqlDataSource);
            }
            connectorMap.put(sqlDataSource.getName(), connector);
        }
    }

    /**
     * 根据名字获取数据源连接器
     * @param name
     * @return
     */
    public Optional<SQLDataSourceConnector> getConnector(String name) {
        if (!connectorMap.containsKey(name)) {
            throw new NoSuchElementException(name);
        }
        return Optional.ofNullable(connectorMap.get(name));
    }

    /**
     * 获取所有数据源连接器
     * @return
     */
    public List<SQLDataSourceConnector> getConnectors() {
        return CommonUtil.values(connectorMap);
    }

    @PreDestroy
    public void onDestroy() {
        for (SQLDataSourceConnector connector : connectorMap.values()) {
            connector.onDestroy();
        }
    }
}
